package com.dubbo.server.service.Impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dubbo.server.mapper.FreezeUserMapper;
import com.dubbo.server.mapper.UserUnfreezeMapper;
import com.dubbo.server.pojo.UserFreeze;
import com.dubbo.server.pojo.UserUnfreeze;
import com.dubbo.server.service.map.BackstageUserMapp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


@Service
public class BackstageUserImpl implements BackstageUserMapp {
    @Autowired
    private FreezeUserMapper freezeUserMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserUnfreezeMapper userUnfreezeMapper;


    private String FREEZE_USER_KEY = "FREEZE_USER_";

    /**
     * 用户冻结
     *
     * @param userId
     * @param freezingTime
     * @param freezingRange
     * @param reasonsForFreezing
     * @param frozenRemarks
     * @return
     */
    @Override
    public Boolean userFreeze(Long userId, Integer freezingTime, Integer freezingRange, String reasonsForFreezing, String frozenRemarks) {
        if (this.queryUserIsFreeze(userId)) {
            return false;// 已经被冻结，操作失败，返回false
        }
        // 向冻结表添加数据
        UserFreeze userFreeze = new UserFreeze();
        userFreeze.setUserId(userId);
        userFreeze.setFreezingTime(freezingTime);
        userFreeze.setFreezingRange(freezingRange);
        userFreeze.setReasonsForFreezing(reasonsForFreezing);
        userFreeze.setFrozenRemarks(frozenRemarks);
//        userFreeze.setUserStatus(UserStatus.FROZEN.getValue());
        userFreeze.setCreated(DateUtil.date(System.currentTimeMillis()));
        userFreeze.setUpdated(DateUtil.date(System.currentTimeMillis()));
        // 将冻结标记写入Redis
        // 将数据写入数据库
        int insert = freezeUserMapper.insert(userFreeze);
        if (insert > 0) {
            String redisKey = FREEZE_USER_KEY + userId;
            this.redisTemplate.opsForValue().set(redisKey, "FREEZE");
        }
        return insert > 0;
    }

    /**
     * 用户解冻
     *
     * @param userId
     * @param reasonsForThawing
     * @return
     */
    @Override
    public Boolean userUnfreeze(Long userId, String reasonsForThawing) {
        if (!this.queryUserIsFreeze(userId)) {
            return false;// 没有被冻结，操作失败，返回false
        }
        // 解冻表新增记录
        UserUnfreeze userUnfreeze = new UserUnfreeze();
        userUnfreeze.setUserId(userId);
        userUnfreeze.setReasonsForThawing(reasonsForThawing);
        userUnfreeze.setUnFreezingTime(DateUtil.date(System.currentTimeMillis()));
        int insert = userUnfreezeMapper.insert(userUnfreeze);
        // 冻结表修改记录
        UpdateWrapper<UserFreeze> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", userId);
        int update = freezeUserMapper.delete(updateWrapper);
        if (update > 0) {
            // 删除redis的冻结标记
            String redisKey = FREEZE_USER_KEY + userId;
            redisTemplate.delete(redisKey);
        }
        return insert > 0 && update > 0;
    }

    /**
     * 判断用户是否冻结
     *
     * @param userId
     * @return
     */
    @Override
    public Boolean queryUserIsFreeze(Long userId) {
        String redisKey = FREEZE_USER_KEY + userId;
        if (this.redisTemplate.hasKey(redisKey)) {
            return true;
        }
        if (ObjectUtil.isNotEmpty(queryFreezeUserById(userId))) {
            return true;
        }
        return false;
    }

    // 获取冻结用户最新信息
    public UserFreeze queryFreezeUserById(Long userId) {
        QueryWrapper<UserFreeze> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId).orderByDesc("updated").last("limit 1");
        return freezeUserMapper.selectOne(queryWrapper);
    }

}
